#    Copyright 2013 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Misc, COOPIP_Form, COOPIP_Authentication
import djangoproject.models.intranet, djangoproject.models.ipbase, djangoproject.models.revenueprotection
from django.contrib.gis.geos import *



def BuildMessageBoardForm(SpecialBuildFormDataDict):
    Dict={}
    Dict['UpdateIndicator']=forms.BooleanField(required=False)
    Dict['CrewList']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['EngineerList']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['ServiceWorkerList']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['Message']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['OutOfOffice']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['ServiceWorkerHours']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    Dict['OnCallList']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'10', 'cols':'80'}))
    return Dict

def ProcessMessageBoardForm(form, Username, request):
    UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator')
    CrewList=COOPIP_Form.FormGetString(form, 'CrewList')
    EngineerList=COOPIP_Form.FormGetString(form, 'EngineerList')
    ServiceWorkerList=COOPIP_Form.FormGetString(form, 'ServiceWorkerList')
    Message=COOPIP_Form.FormGetString(form, 'Message')
    OutOfOffice=COOPIP_Form.FormGetString(form, 'OutOfOffice')
    ServiceWorkerHours=COOPIP_Form.FormGetString(form, 'ServiceWorkerHours')
    OnCallList=COOPIP_Form.FormGetString(form, 'OnCallList')
    if(UpdateIndicator):
        dispatchBoardForm=djangoproject.models.intranet.DispatchBoard()
        dispatchBoardForm.CrewList=CrewList
        dispatchBoardForm.EngineerList=EngineerList
        dispatchBoardForm.ServiceWorkerList=ServiceWorkerList
        dispatchBoardForm.Message=Message
        dispatchBoardForm.OutOfOffice=OutOfOffice
        dispatchBoardForm.ServiceWorkerHours=ServiceWorkerHours
        dispatchBoardForm.OnCallList=OnCallList
        dispatchBoardForm.CreateUsername=Username
        dispatchBoardForm.CreateDateTime=datetime.datetime.now()
        dispatchBoardForm.save()


def PopulateMessageBoardForm(form):
    form.data['UpdateIndicator']=False
    DispatchBoards=djangoproject.models.intranet.DispatchBoard.objects.all().order_by('-CreateDateTime')
    if(DispatchBoards.count()):
        form.setData({'CrewList': DispatchBoards[0].CrewList})
        form.setData({'EngineerList': DispatchBoards[0].EngineerList})
        form.setData({'ServiceWorkerList': DispatchBoards[0].ServiceWorkerList})
        form.setData({'Message': DispatchBoards[0].Message})
        form.setData({'OutOfOffice': DispatchBoards[0].OutOfOffice})
        form.setData({'ServiceWorkerHours': DispatchBoards[0].ServiceWorkerHours})
        form.setData({'OnCallList': DispatchBoards[0].OnCallList})
    else:
        form.data['CrewList']=''
        form.data['EngineerList']=''
        form.data['ServiceWorkerList']=''
        form.data['Message']=''
        form.data['OutOfOffice']=''
        form.data['ServiceWorkerHours']=''
        form.data['OnCallList']=''
    return form


def BuildVehicleForm(SpecialBuildFormDataDict):
    Dict={}
    for i in range(0, len(SpecialBuildFormDataDict['Vehicles'])):
        Dict['UpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['Vehicleid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['Name' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
        Dict['Number' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['LatestLogDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15', 'READONLY':'True'}))
        Dict['Status' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15', 'READONLY':'True'}))
        Dict['NearestRoadName' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15', 'READONLY':'True'}))
    return Dict

def ProcessVehicleForm(form, Username, Vehicles):
    for i in range(0, len(Vehicles)):
        UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator' + str(i))
        if(UpdateIndicator):
            vehicle=COOPIP_Form.FormGetObjectFromid(form, 'Vehicleid' + str(i), djangoproject.models.ipbase.Vehicle)
            Name = COOPIP_Form.FormGetString(form, 'Name' + str(i))
            vehicle.Name = Name
            vehicle.save()

def PopulateVehicleForm(form, Vehicles):
    for i in range(0, len(Vehicles)):
        form.data['UpdateIndicator' + str(i)]=False
        form.setData({'Vehicleid' + str(i): Vehicles[i].id})
        form.data['Name' + str(i)]=Vehicles[i].Name
        form.data['Number' + str(i)]=Vehicles[i].Number
        FormattedDateTime = Vehicles[i].LatestLogDateTime.strftime('%m/%d/%Y %H:%M')
        form.data['LatestLogDateTime' + str(i)]=FormattedDateTime
        form.data['Status' + str(i)]=Vehicles[i].Symbology
        form.data['NearestRoadName' + str(i)]=Vehicles[i].NearestRoadName
    return form


def BuildCrewLogForm(SpecialBuildFormDataDict):
    import datetime
    Now=datetime.datetime.now()
    StartTime=Now - datetime.timedelta(hours=18)
    EndTime=Now
    DispatchCrewLogs=SpecialBuildFormDataDict['DispatchCrewLogs']
    Dict={}
    Dict['NewIndicator']=forms.BooleanField(required=False)
    Dict['CrewNumberNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['TruckNumberNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['EmployeesNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'22'}))
    Dict['EnRouteDateTimeNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['ArriveAtLocationDateTimeNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['DepartLocationDateTimeNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
    Dict['LocationDescriptionNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    Dict['PoleNumberNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['AddressNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'28'}))
    Dict['BackAtOfficeDateTimeNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['CommentsNew']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'35'}))
    for count in range(0, DispatchCrewLogs.count()):
        Dict['UpdateIndicator' + str(count)]=forms.BooleanField(required=False)
        Dict['DispatchCrewLogid' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))
        Dict['CrewNumber' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['TruckNumber' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['Employees' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'22'}))
        Dict['EnRouteDateTime' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ArriveAtLocationDateTime' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['DepartLocationDateTime' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8'}))
        Dict['LocationDescription' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
        Dict['PoleNumber' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['Address' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'28'}))
        Dict['BackAtOfficeDateTime' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['Comments' + str(count)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'35'}))
        Dict['DeleteIndicator' + str(count)]=forms.BooleanField(required=False)
    return Dict



class FakeForm():
    def __init__(self, data):
        self.data=data

def ProcessCrewLogForm(form, Username, request):
    if not (request.method == 'POST'):  
        return 
    form=FakeForm(request.POST)  #Process from the request, as the number of logs in the request may be different from the number on the server.
    NewIndicator=COOPIP_Form.FormGetBoolean(form, 'NewIndicator')
    CrewNumber=COOPIP_Form.FormGetString(form, 'CrewNumberNew')
    TruckNumber=COOPIP_Form.FormGetString(form, 'TruckNumberNew')
    Employees=COOPIP_Form.FormGetString(form, 'EmployeesNew')
    EnRouteDateTime=COOPIP_Form.FormGetDateTime2(form, 'EnRouteDateTimeNew')
    ArriveAtLocationDateTime=COOPIP_Form.FormGetDateTime2(form, 'ArriveAtLocationDateTimeNew')
    DepartLocationDateTime=COOPIP_Form.FormGetDateTime2(form, 'DepartLocationDateTimeNew')
    LocationDescription=COOPIP_Form.FormGetString(form, 'LocationDescriptionNew')
    PoleNumber=COOPIP_Form.FormGetInteger(form, 'PoleNumberNew')
    Address=COOPIP_Form.FormGetString(form, 'AddressNew')
    BackAtOfficeDateTime=COOPIP_Form.FormGetDateTime2(form, 'BackAtOfficeDateTimeNew')
    Comments=COOPIP_Form.FormGetString(form, 'CommentsNew')
    if(NewIndicator):
        New=djangoproject.models.intranet.DispatchCrewLog()
        New.CrewNumber=CrewNumber
        if(TruckNumber):
            New.TruckNumber=TruckNumber
            New.TruckNumberLastModifyDateTime=datetime.datetime.now()
        else:
            Previous=djangoproject.models.intranet.DispatchCrewLog.objects.filter(CrewNumber=CrewNumber).order_by('-CreateDateTime')
            if(Previous):
                New.TruckNumber=Previous[0].TruckNumber
                New.TruckNumberLastModifyDateTime=Previous[0].TruckNumberLastModifyDateTime
        New.Employees=Employees
        New.EnRouteDateTime=EnRouteDateTime
        New.ArriveAtLocationDateTime=ArriveAtLocationDateTime
        New.DepartLocationDateTime=DepartLocationDateTime
        New.LocationDescription=LocationDescription
        New.PoleNumber=PoleNumber
        New.Address=Address
        New.BackAtOfficeDateTime=BackAtOfficeDateTime
        New.Comments=Comments
        New.CreateDateTime=datetime.datetime.now()
        New.LastModifyDateTime=New.CreateDateTime
        New.save()
    count = -1
    while True:
        count = count + 1
        if(not form.data.has_key('CrewNumber' + str(count))):
            break
        UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator' + str(count))
        if(not UpdateIndicator):
            continue
        DispatchCrewLogid=COOPIP_Form.FormGetInteger(form, 'DispatchCrewLogid' + str(count))
        dispatchCrewLog=djangoproject.models.intranet.DispatchCrewLog.objects.filter(id=DispatchCrewLogid)[0]
        if(dispatchCrewLog.CreateDateTime < datetime.datetime.now() - datetime.timedelta(days=4)):
            continue
        dispatchCrewLog.CrewNumber=COOPIP_Form.FormGetString(form, 'CrewNumber' + str(count))
        TruckNumber=COOPIP_Form.FormGetString(form, 'TruckNumber' + str(count))
        if(not TruckNumber == dispatchCrewLog.TruckNumber):
            dispatchCrewLog.TruckNumber=TruckNumber
            dispatchCrewLog.TruckNumberLastModifyDateTime=datetime.datetime.now()
        dispatchCrewLog.Employees=COOPIP_Form.FormGetString(form, 'Employees' + str(count))
        dispatchCrewLog.EnRouteDateTime=COOPIP_Form.FormGetDateTime2(form, 'EnRouteDateTime' + str(count))
        dispatchCrewLog.ArriveAtLocationDateTime=COOPIP_Form.FormGetDateTime2(form, 'ArriveAtLocationDateTime' + str(count))
        dispatchCrewLog.DepartLocationDateTime=COOPIP_Form.FormGetDateTime2(form, 'DepartLocationDateTime' + str(count))
        dispatchCrewLog.LocationDescription=COOPIP_Form.FormGetString(form, 'LocationDescription' + str(count))
        dispatchCrewLog.PoleNumber=COOPIP_Form.FormGetInteger(form, 'PoleNumber' + str(count))
        dispatchCrewLog.Address=COOPIP_Form.FormGetString(form, 'Address' + str(count))
        
        dispatchCrewLog.BackAtOfficeDateTime=COOPIP_Form.FormGetDateTime2(form, 'BackAtOfficeDateTime' + str(count))
        dispatchCrewLog.Comments=COOPIP_Form.FormGetString(form, 'Comments' + str(count))
        dispatchCrewLog.LastModifyDateTime=datetime.datetime.now()
        dispatchCrewLog.DeletedIndicator=COOPIP_Form.FormGetBoolean(form, 'DeleteIndicator' + str(count))
        dispatchCrewLog.save()



def PopulateCrewLogForm(form, DispatchCrewLogs):
    form.data['NewIndicator']=False
    form.data['CrewNumberNew']=''
    form.data['TruckNumberNew']=''
    form.data['EmployeesNew']=''
    form.data['EnRouteDateTimeNew']=''
    form.data['ArriveAtLocationDateTimeNew']=''
    form.data['DepartLocationDateTimeNew']=''
    form.data['LocationDescriptionNew']=''
    form.data['PoleNumberNew']=''
    form.data['AddressNew']=''
    form.data['BackAtOfficeDateTimeNew']=''
    form.data['CommentsNew']=''
    a = []
    for i in DispatchCrewLogs:
        a.append(i.id)
    #raise(Exception(str(a)))
    for count in range(0, DispatchCrewLogs.count()):
        form.setData({'UpdateIndicator' + str(count): False})
        form.setData({'DispatchCrewLogid' + str(count): DispatchCrewLogs[count].id})
        
        form.setData({'CrewNumber' + str(count): DispatchCrewLogs[count].CrewNumber})
        form.setData({'TruckNumber' + str(count): DispatchCrewLogs[count].TruckNumber})
        form.setData({'Employees' + str(count): DispatchCrewLogs[count].Employees})
        if(DispatchCrewLogs[count].EnRouteDateTime):
            form.setData({'EnRouteDateTime' + str(count): DispatchCrewLogs[count].EnRouteDateTime.strftime('%H:%M')})
        else:
            form.setData({'EnRouteDateTime' + str(count): ''})

        if(DispatchCrewLogs[count].ArriveAtLocationDateTime):
            form.setData({'ArriveAtLocationDateTime' + str(count): DispatchCrewLogs[count].ArriveAtLocationDateTime.strftime('%H:%M')})
        else:
            form.setData({'ArriveAtLocationDateTime' + str(count): ''})
        if(DispatchCrewLogs[count].DepartLocationDateTime):
            form.setData({'DepartLocationDateTime' + str(count): DispatchCrewLogs[count].DepartLocationDateTime.strftime('%H:%M')})
        else:
            form.setData({'DepartLocationDateTime' + str(count): ''})
    
        form.setData({'LocationDescription' + str(count): DispatchCrewLogs[count].LocationDescription})
        form.setData({'PoleNumber' + str(count): DispatchCrewLogs[count].PoleNumber})
        form.setData({'Address' + str(count): DispatchCrewLogs[count].Address})
        if(DispatchCrewLogs[count].BackAtOfficeDateTime):
            form.setData({'BackAtOfficeDateTime' + str(count): DispatchCrewLogs[count].BackAtOfficeDateTime.strftime('%H:%M')})
        else:
            form.setData({'BackAtOfficeDateTime' + str(count): ''})
        if(DispatchCrewLogs[count].Comments):
            form.setData({'Comments' + str(count): DispatchCrewLogs[count].Comments})
        else:
            form.setData({'Comments' + str(count): ''})
        form.setData({'DeleteIndicator' + str(count): False})
    return form


def BuildAlarmForm(SpecialBuildFormDataDict):
    Dict={}
    #Dict['PingMeterCommand'] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12'}))
    for i in range(0, len(SpecialBuildFormDataDict['Alarms'])):
        Dict['UpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['Alarmid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['AlarmArmIndicator' + str(i)]=forms.BooleanField()
        Dict['AlarmDisarmIndicator' + str(i)]=forms.BooleanField()
        Dict['AlarmAcknowledgeIndicator' + str(i)]=forms.BooleanField()
        Dict['AlarmCloseIndicator' + str(i)] = forms.BooleanField()
        Dict['AlarmEventDescription' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':'2', 'cols':'50'}))
    return Dict

def ProcessAlarmForm(form, Username):
    i = 0
    while(True):
        if(not form.data.has_key('Alarmid' + str(i))):
            break

        UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator' + str(i))
        if(UpdateIndicator):

            alarm=COOPIP_Form.FormGetObjectFromid(form, 'Alarmid' + str(i), djangoproject.models.networkdevice.NetworkDevice)
            AlarmArmIndicator=COOPIP_Form.FormGetBoolean(form, 'AlarmArmIndicator' + str(i))
            
            AlarmDisarmIndicator=COOPIP_Form.FormGetBoolean(form, 'AlarmDisarmIndicator' + str(i))
            AlarmAcknowledgeIndicator=COOPIP_Form.FormGetBoolean(form, 'AlarmAcknowledgeIndicator' + str(i))
            AlarmCloseIndicator=COOPIP_Form.FormGetBoolean(form, 'AlarmCloseIndicator' + str(i))
            AlarmDescription=COOPIP_Form.FormGetString(form, 'AlarmEventDescription' + str(i))
            #Do update stuff here
            alarmEventHistory=alarm.GetOpenAlarmEventHistory()

            if(alarmEventHistory):
                if(AlarmAcknowledgeIndicator or AlarmDisarmIndicator or AlarmCloseIndicator or AlarmDescription):
                    if(not alarmEventHistory.AcknowledgeDateTime):
                        alarmEventHistory.AcknowledgeDateTime = datetime.datetime.now()
                        alarmEventHistory.AcknowledgeUsername = Username
                        alarmEventHistory.PendingAcknowledgeNotification = True
                if(AlarmArmIndicator):
                    alarm.PendingArmUsername = Username
                    alarm.save()
                if(AlarmDisarmIndicator):
                    alarm.PendingDisarmUsername=Username
                    alarm.save()
                    if(not alarmEventHistory.DisarmDateTime):
                        alarmEventHistory.DisarmDateTime = datetime.datetime.now()
                        alarmEventHistory.DisarmUsername = Username
                if(AlarmCloseIndicator):
                    if(not alarmEventHistory.CloseDateTime):
                        alarmEventHistory.CloseDateTime = datetime.datetime.now()
                        alarmEventHistory.CloseUsername = Username
                alarmEventHistory.Description = AlarmDescription
                alarmEventHistory.save()
            else:  #If no alarm event, just allow the alarm to be armed and disarmed
                if(AlarmArmIndicator):
                    alarm.PendingArmUsername = Username
                    alarm.save()
                if(AlarmDisarmIndicator):
                    alarm.PendingDisarmUsername = Username
                    alarm.save()
        i = i + 1  #Next Alarm

def PopulateAlarmForm(form, Alarms):
    for i in range(0, len(Alarms)):
        form.data['UpdateIndicator' + str(i)]=False
        #form.data['Alarmid' + str(i)]=Alarms[i].id
        form.setData({'Alarmid' + str(i): Alarms[i].id})
        form.setData({'AlarmArmIndicator' + str(i): False})
        form.setData({'AlarmDisarmIndicator' + str(i): False})
        alarmEventHistory=Alarms[i].GetOpenAlarmEventHistory()
        if(alarmEventHistory):
            form.setData({'AlarmAcknowledgeIndicator' + str(i): bool(alarmEventHistory.AcknowledgeDateTime)})
            form.setData({'AlarmEventDescription' + str(i): alarmEventHistory.Description})
        else:
            form.setData({'AlarmAcknowledgeIndicator' + str(i): False})
            form.setData({'AlarmEventDescription' + str(i): ''})
    return form


def BuildAlarmContactForm(SpecialBuildFormDataDict):
    Dict={}
    for i in range(0, len(SpecialBuildFormDataDict['Groups'])):
        Dict['UpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['Groupid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['PriorityLevel' + str(i)]=forms.IntegerField()
        Dict['EscalationIntervalSeconds' + str(i)]=forms.FloatField()
        Dict['Recipients' + str(i)]=forms.CharField(widget=forms.Textarea(attrs={'rows':'6', 'cols':'50'}))
    return Dict

def ProcessAlarmContactForm(form, Username, Groups):
    for i in range(0, len(Groups)):
        UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator' + str(i))
        if(UpdateIndicator):
            group=COOPIP_Form.FormGetObjectFromid(form, 'Groupid' + str(i), djangoproject.models.networkdevice.AlarmContactGroup)
            PriorityLevel=COOPIP_Form.FormGetInteger(form, 'PriorityLevel' + str(i))
            EscalationIntervalSeconds=COOPIP_Form.FormGetFloat(form, 'EscalationIntervalSeconds' + str(i))
            group.PriorityLevel=PriorityLevel
            group.EscalationIntervalSeconds=EscalationIntervalSeconds
            group.Recipients=COOPIP_Form.FormGetString(form, 'Recipients' + str(i))
            group.save()

def PopulateAlarmContactForm(form, Groups):
    for i in range(0, len(Groups)):
        form.data['UpdateIndicator' + str(i)]=False
        form.setData({'Groupid' + str(i): Groups[i].id})
        form.data['PriorityLevel' + str(i)] = Groups[i].PriorityLevel
        form.data['EscalationIntervalSeconds' + str(i)] = Groups[i].EscalationIntervalSeconds
        form.data['Recipients' + str(i)] = Groups[i].Recipients
    return form


def BuildOutageAssignmentForm(SpecialBuildFormDataDict):
    Dict={}
    for i in range(0, len(SpecialBuildFormDataDict['Logs'])):
        Dict['UpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['Logid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['Incidentid' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10', 'READONLY':'True'}))
        Dict['MeterNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['MapNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15', 'READONLY':'True'}))
        Dict['CreateDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15', 'READONLY':'True'}))
        Dict['AssignedTo' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
        Dict['AssignedDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15', 'READONLY':'True'}))
    return Dict

def ProcessOutageAssignmentForm(form, Username, Logs):
    for i in range(0, len(Logs)):
        UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator' + str(i))
        if(UpdateIndicator):
            Log=COOPIP_Form.FormGetObjectFromid(form, 'Logid' + str(i), djangoproject.models.ipbase.OMSIncidentHistory)
            Log.AssignedTo = COOPIP_Form.FormGetString(form, 'AssignedTo' + str(i))
            Log.AssignedDateTime = datetime.datetime.now()
            Log.save()

def PopulateOutageAssignmentForm(form, Logs):
    for i in range(0, len(Logs)):
        form.data['UpdateIndicator' + str(i)]=False
        form.setData({'Logid' + str(i): Logs[i].id})
        form.data['Incidentid' + str(i)]=Logs[i].Incidentid
        form.data['MeterNumber' + str(i)]=Logs[i].MeterNumber
        form.data['MapNumber' + str(i)]=Logs[i].MapNumber
        Created = Logs[i].CreateDateTime.strftime('%m/%d/%Y %H:%M')
        form.data['CreateDateTime' + str(i)]=Created
        form.data['AssignedTo' + str(i)] = str(Logs[i].AssignedTo)
        if Logs[i].AssignedDateTime:
            Assigned = Logs[i].AssignedDateTime.strftime('%m/%d/%Y %H:%M')
            form.data['AssignedDateTime' + str(i)]=Assigned
        else:
            form.data['AssignedDateTime' + str(i)] = ''
    return form



def BuildDynamicCircuitAssignmentForm():
    Dict={}
    Dict['NormalGISCircuitNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['AlternativeGISCircuitNumberList']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    return Dict



def ProcessDynamicCircuitAssignmentForm(form, Username):
    NormalGISCircuitNumber = COOPIP_Form.FormGetString(form, 'NormalGISCircuitNumber')
    AlternativeGISCircuitNumberList = COOPIP_Form.FormGetString(form, 'AlternativeGISCircuitNumberList')
    ExistingMeterPingDynamicCircuit = djangoproject.models.ipbase.MeterPingDynamicCircuit.objects.filter(NormalGISCircuitNumber=NormalGISCircuitNumber)
    if(ExistingMeterPingDynamicCircuit):
        Existing = ExistingMeterPingDynamicCircuit[0]
        if(not AlternativeGISCircuitNumberList):
            Existing.ClearMetersWithAlternativeCircuits()
            Existing.delete()
        else:
            Existing.ClearMetersWithAlternativeCircuits()
            Existing.AlternativeGISCircuitNumberList = AlternativeGISCircuitNumberList
            Existing.save()
            Existing.UpdateMetersWithAlternativeCircuits()
    elif(NormalGISCircuitNumber):
        New=djangoproject.models.ipbase.MeterPingDynamicCircuit()
        New.NormalGISCircuitNumber = NormalGISCircuitNumber
        New.AlternativeGISCircuitNumberList = AlternativeGISCircuitNumberList
        New.save()
        New.UpdateMetersWithAlternativeCircuits()




def PopulateDynamicCircuitAssignmentForm(form):
    form.data['NormalGISCircuitNumber'] = ''
    form.data['AlternativeGISCircuitNumberList'] = ''
    return form


